import { message } from "antd";
import type {
  AxiosInstance,
  AxiosRequestConfig,
  AxiosResponse,
  InternalAxiosRequestConfig,
} from "axios";
import axios from "axios";
import qs from "qs";

class Service {
  instance: AxiosInstance;
  baseConfig: AxiosRequestConfig = {
    // baseURL: "https://wanandroid.com",
    timeout: 4000,
    responseType: "json",
    params: {},
    maxContentLength: 2000,
    validateStatus: (status) => status >= 200 && status < 300, //默认值
    maxRedirects: 5, //最大允许重定向次数
    headers: {
      "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
    },
  };

  constructor(config: AxiosRequestConfig) {
    this.instance = axios.create(Object.assign(this.baseConfig, config));

    this.instance.interceptors.request.use(
      (request: InternalAxiosRequestConfig) => {
        // 在发送请求前做些什么
        const token = localStorage.getItem("token");
        if (token) {
          request.headers.Authorization = `Bearer ${token}`;
        }
        return request;
      },
      (err: any) => {
        return Promise.reject(err);
      }
    );

    this.instance.interceptors.response.use(
      (res: AxiosResponse) => {
        return res.data.errorCode === 0
          ? res.data.data
          : Promise.reject(res.data.errorMsg);
      },
      (err: any) => {
        let msg = `连接出错(${err.response.status})!`;
        if (err.response.status in ErrState)
          msg = ErrState[err.response.status]();
        message.error(msg);
        return Promise.reject(err.response);
      }
    );
  }

  public request(
    url: string,
    method: string,
    data: any = null
  ): Promise<AxiosResponse> {
    if (data) data = qs.stringify(data);
    return this.instance.request({
      url: url,
      method: method,
      data: data,
    });
  }
}

export default Service;

const ErrState: { [key: string]: any } = {
  401: function () {
    setTimeout(() => {
      localStorage.setItem("token", "");
      // 注意 ajax中不能使用 react-router-dom  只能原生跳转
      // window.location.replace("/#" + RouterPath.login);
    }, 2000);
    return "未授权或凭证过期，请重新登录(401)";
  },
  404: function () {
    return "未找到(404)";
  },
};
